<template>
  <div style="height: 100%; width: 100%; overflow-x: auto;">

    <el-form :model="form" label-width="100px" inline>
      <el-form-item label="住院号" prop="hospitalNumber">
        <el-input v-model="form.hospitalNumber" placeholder="请输入住院号" style="width: 120px;" clearable @clear="clearHospitalNumber" />
      </el-form-item>

      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别" style="width: 120px;">
          <el-option label="全部" value="全部" />
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="form.idCard" placeholder="请输入身份证号" style="width: 200px;" clearable @clear="clearIdCard" />
      </el-form-item>

      <el-form-item label="创建时间" prop="createTimeRange">
        <el-date-picker
          v-model="form.createTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
        :key="tableKey"
        :data="nurseInfo"
        border
        style="width: 100%;"
        :height="tableHeight"
        :row-style="{ height: '50px' }"
        :cell-style="{ padding: '0' }">
      <el-table-column
          v-for="(column, index) in columns"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.minWidth">
        <template v-slot:default="scope">
          <!-- 特殊处理病理结果列 -->
          <template v-if="column.prop === 'pathologyResult' || column.prop === 'postoperativePathologyResult'">
            <el-image
                :src="scope.row[column.prop]"
                :preview-src-list="[scope.row[column.prop]]"
                preview-teleported
                style="width: 100px; height: 100px;"
                fit="contain"
            ></el-image>
          </template>
          <template v-else>
            {{ scope.row[column.prop] }}
          </template>
        </template>

        <template #default="scope" v-if="['surgeryDate'].includes(column.prop)">
          <div class="text-wrap">{{ scope.row[column.prop] }}</div>
        </template>
        
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          min-width="120px">
        <template v-slot:default="scope">
          <el-button v-if="!isBatchDeleteMode" type="text" size="medium">查看</el-button>
          <el-button
              v-if="!isBatchDeleteMode"
              @click="handleDelete(scope.row)"
              type="text"
              size="medium"
          >删除</el-button>
          <el-checkbox
              v-if="isBatchDeleteMode"
              :checked="isRowSelected(scope.row.id)"
              @change="(val) => handleSelectionChange(scope.row.id, val)"
          ></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px;">
      <el-col :span="18">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
      </el-col>
      <el-col :span="6" style="text-align: right;">
        <el-button
            v-if="!isBatchDeleteMode"
            type="danger"
            @click="enterBatchDeleteMode">
          批量删除
        </el-button>
        <template v-else>
          <el-button type="danger" @click="confirmBatchDelete">确定删除</el-button>
          <el-button @click="cancelBatchDelete">取消</el-button>
        </template>
        <el-button
            type="primary"
            @click="exportDialogVisible = true"
            :disabled="isBatchDeleteMode">
          导出Excel
        </el-button>
      </el-col>
    </el-row>
    <el-dialog title="选择时间范围" v-model="exportDialogVisible" width="30%" align-center>
      <el-form>
        <el-form-item label="开始时间">
          <el-date-picker
              v-model="startTime"
              type="date"
              placeholder="选择开始时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
              v-model="endTime"
              type="date"
              placeholder="选择结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="exportExcel">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue';
import { apiClient } from '../api/apiClient.ts' // 引入 apiClient 实例
import {downloadClient} from'../api/downloadClient'


export default {
  name: 'ProstateCancer',
  data() {
    return {
      tableKey: 0,
      form: {
        hospitalNumber: "全部",
        gender: "全部",
        idCard: "全部",
        createTimeRange: ["", ""], // 开始日期和结束日期
      },
      selectedIds: new Set(), // 全局存储选中的id
      isBatchDeleteMode: false,
      exportDialogVisible: false,
      startTime: '',
      endTime: '',
      page: 1, // 当前页码
      size: 10, // 每页显示的记录数
      total: 0, // 总记录数
      allNurseInfo: [], // 用于存储从后端获取的所有数据
      nurseInfo: [], // 用于存储当前页的数据
      tableHeight: 'calc(100% - 50px)', // 计算表格高度，减去分页组件的高度
      columns: [
        { prop: 'hospitalNumber', label: '住院号', minWidth: '80px' },
        { prop: 'gender', label: '性别', minWidth: '60px' },
        { prop: 'age', label: '年龄', minWidth: '60px' },
        { prop: 'idCard', label: '身份证号', minWidth: '120px' },
        { prop: 'surgeryDate', label: '手术日期', minWidth: '180px' },
        { prop: 'disease', label: '原发病', minWidth: '120px' },
        { prop: 'address', label: '通信地址', minWidth: '120px' },
        { prop: 'phone', label: '电话', minWidth: '120px' },
        { prop: 'name', label: '姓名', minWidth: '80px' },
        { prop: 'reVisitsNum', label: '回访次数', minWidth: '80px' },
        { prop: 'diagnosisMethod', label: '确诊方式', minWidth: '120px' },
        { prop: 'pathologyResult', label: '病理结果', minWidth: '120px' },
        { prop: 'diagnosisTime', label: '确诊时间', minWidth: '120px' },
        { prop: 'psaAtDiagnosis', label: '确诊PSA值', minWidth: '120px' },
        { prop: 'preoperativeMedication', label: '术前用药', minWidth: '80px' },
        { prop: 'beforeMedicationName', label: '术前药物名称', minWidth: '120px' },
        { prop: 'beforeMedicationStartTime', label: '术前用药开始时间', minWidth: '120px' },
        { prop: 'psaAfterMedication', label: '用药后PSA值', minWidth: '120px' },
        { prop: 'surgeryType', label: '手术方式', minWidth: '120px' },
        { prop: 'surgeryTime', label: '手术时间', minWidth: '120px' },
        { prop: 'postoperativePathologyResult', label: '术后病理结果', minWidth: '120px' },
        { prop: 'urinaryIncontinenceAfterSurgery', label: '术后尿失禁', minWidth: '80px' },
        { prop: 'urinaryPadNumber', label: '尿垫数量', minWidth: '80px' },
        { prop: 'recoveryTimeWithoutPad', label: '恢复时间', minWidth: '120px' },
        { prop: 'otherPostoperativeDiscomfort', label: '其他不适', minWidth: '120px' },
        { prop: 'postoperativeMedication', label: '术后用药', minWidth: '80px' },
        { prop: 'afterMedicationName', label: '术后药物名称', minWidth: '120px' },
        { prop: 'afterMedicationStarttime', label: '术后用药开始时间', minWidth: '120px' },
        { prop: 'psaRecheckTime', label: 'PSA复查时间', minWidth: '120px' },
        { prop: 'psaRecheckValue', label: 'PSA复查数值', minWidth: '120px' },
        { prop: 'createTime', label: '创建时间', minWidth: '120px' }
      ]
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    clearHospitalNumber() {
            this.form.hospitalNumber = '全部'
         },
        clearIdCard() { 
            this.form.idCard = '全部'
        },
    // 进入批量删除模式
    enterBatchDeleteMode() {
      this.isBatchDeleteMode = true;
      this.selectedIds = new Set(); // 重置选择状态
    },

    // 处理选择状态变化
    handleSelectionChange(id, isSelected) {
      if (isSelected) {
        this.selectedIds.add(id);
      } else {
        this.selectedIds.delete(id);
      }
    },

    // 判断行是否被选中
    isRowSelected(id) {
      return this.selectedIds.has(id);
    },

    // 取消批量删除
    cancelBatchDelete() {
      this.isBatchDeleteMode = false;
      this.selectedIds = new Set(); // 清空选择
    },

    // 确认批量删除
    confirmBatchDelete() {
      if (this.selectedIds.size === 0) {
        this.$message.warning('请选择删除的数据');
        return;
      }

      this.$confirm('你确定删除这些数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteItems([...this.selectedIds]); // 将Set转为数组
      }).catch(() => {});
    },

    // 单条删除处理
    handleDelete(row) {
      this.$confirm('你确定删除该数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteItems([row.id]);
      }).catch(() => {});
    },

    // 删除API调用
    deleteItems(ids) {
      const apiEndpoint = '/doctor/deletPatientInfoProstateCancerList/';

      apiClient.post(apiEndpoint, ids)
          .then(response => {
            if (response.data.code === 1) {
              this.$message.success('删除成功');
              this.isBatchDeleteMode = false;
              // 删除成功后清除相关选择状态
              ids.forEach(id => this.selectedIds.delete(id));
              this.fetchData();
            } else {
              this.$message.error('删除失败: ' + response.data.msg);
            }
          })
          .catch(error => {
            console.error('删除失败:', error);
            this.$message.error('删除失败，请稍后重试');
          });
    },

    exportExcel() {
      if (!this.startTime || !this.endTime) {
        this.$message.error('请选择开始时间和结束时间');
        return;
      }
      this.$message.info('正在下载Excel...');
      downloadClient('/doctor/export',
          { startTime: this.startTime, endTime: this.endTime ,exportType: "type1"},
          `病人信息_${this.startTime}_${this.endTime}.xlsx`
      ).then(() => {
        this.$message.success('下载成功');
      }).catch(() => {
        this.$message.error('下载失败');
      });
    },
    fetchData() {
      //this.$message.info('正在加载数据...');
      const params = {
        hospitalNumber: this.form.hospitalNumber,
        gender: this.form.gender,  // 修正这里之前错误的hospitalNumber
        idCard: this.form.idCard,
        startTime: this.form.createTimeRange?.[0] || '', // 处理可能为空的日期
        endTime: this.form.createTimeRange?.[1] || ''
      };
      apiClient.get('/doctor/getPatientInfoProstateCancerList/',{ params })
          .then(response => {
            console.log(response)
            if (response.data.code === 1) {
              this.allNurseInfo = response.data.data.map(item => ({
                ...item,
                id: item.id // 确保后端返回了id
              }));
              this.total = this.allNurseInfo.length; // 更新总记录数
              this.getTableData(); // 初始化表格数据
              //this.$message.success('数据加载成功');
            } else {
              console.error('Failed to fetch return visit list:', response.data.msg);
              this.$message.error('获取数据失败，请稍后重试');
            }
          })
          .catch(error => {
            console.error('Failed to fetch return visit list:', error);
            this.$message.error('网络请求失败，请稍后重试');
          });
    },
    handleClick(row) {
      console.log('Row clicked:', row);
      // 示例：弹窗显示详细信息
      this.$alert(JSON.stringify(row, null, 2), '详细信息', {
        dangerouslyUseHTMLString: true
      });
    },
    getTableData() {
      this.nurseInfo = this.allNurseInfo.slice((this.page - 1) * this.size, this.page * this.size);
      this.tableKey++;
    },
    sizeChange(newSize) {
      this.size = newSize;
      this.getTableData();
    },
    currentChange(newPage) {
      this.page = newPage;
      this.getTableData();
    }
  }
};
</script>

<style scoped>
.text-wrap {
  white-space: pre-wrap;
  line-height: 1.5;
  max-height: 120px;
  overflow: auto;
  letter-spacing: normal;
  --characters-per-line: 22;
  width: calc(var(--characters-per-line) * 1ch);
  min-height: 48px; /* 固定最小高度，防止内容过短时块塌陷 */
  display: block;
}
h1 {
  margin-bottom: 20px;
}
</style>